package com.lkyh.mes.codegen.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lkyh.mes.codegen.dto.FormInfo;
import com.lkyh.mes.codegen.dto.QueryFormInfo;
import com.lkyh.mes.codegen.entity.GenTableInfo;
import com.lkyh.mes.codegen.mapper.FormInfoMapper;
import com.lkyh.mes.codegen.service.FormInfoService;
import com.lkyh.mes.codegen.service.GenTableInfoService;
import com.lkyh.mes.common.datasource.support.DynamicDataSourceContextHolder;
import com.lkyh.mes.common.security.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

@Service
//@AllArgsConstructor
@Slf4j
public class FormInfoServiceImpl implements FormInfoService {

	@Resource
	private FormInfoMapper formInfoMapper;
	@Resource
	@Lazy
	private GenTableInfoService genTableInfoService;
	@Resource
	private PlatformTransactionManager platformTransactionManager;

	@Override
	public IPage<List<Map<String, Object>>> page(IPage<FormInfo> page, QueryFormInfo queryFormInfo) {
		GenTableInfo genTableInfo = genTableInfoService.getByIdWithChild(queryFormInfo.getTableId());
		queryFormInfo.setGenTableInfo(genTableInfo);
		DynamicDataSourceContextHolder.setDataSourceType(genTableInfo.getDatasourceId());
		IPage<List<Map<String, Object>>> iPage;
		try {
			iPage = formInfoMapper.page(page, queryFormInfo);
		} finally {
			DynamicDataSourceContextHolder.clearDataSourceType();
		}
		return iPage;
	}

	@Override
	public List<Map<String, Object>> list(QueryFormInfo queryFormInfo) {
		return (List<Map<String, Object>>) this.page(new Page(), queryFormInfo).getRecords();
	}

	@Override
	public Map<String, Object> getOne(QueryFormInfo queryFormInfo) {
		List<Map<String, Object>> list = this.list(queryFormInfo);
		if (CollUtil.isNotEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public Integer save(FormInfo formInfo) {
		GenTableInfo genTableInfo = genTableInfoService.getByIdWithChild(formInfo.getTableId());
		formInfo.setGenTableInfo(genTableInfo);
		formInfo.setUser(SecurityUtils.getUser());
		DynamicDataSourceContextHolder.setDataSourceType(genTableInfo.getDatasourceId());
		try {
			formInfoMapper.insert(formInfo);
		} finally {
			DynamicDataSourceContextHolder.clearDataSourceType();
		}
		return formInfo.getId();
	}

	@Override
	public void update(FormInfo formInfo) {
		GenTableInfo genTableInfo = genTableInfoService.getByIdWithChild(formInfo.getTableId());
		formInfo.setGenTableInfo(genTableInfo);
		DynamicDataSourceContextHolder.setDataSourceType(genTableInfo.getDatasourceId());
		try {
			formInfoMapper.update(formInfo);
		} finally {
			DynamicDataSourceContextHolder.clearDataSourceType();
		}

	}

	@Override
	public void remove(Integer tableId, Integer id) {
		FormInfo formInfo = new FormInfo().setTableId(tableId).setId(id);
		GenTableInfo genTableInfo = genTableInfoService.getByIdWithChild(tableId);
		formInfo.setGenTableInfo(genTableInfo);
		DynamicDataSourceContextHolder.setDataSourceType(genTableInfo.getDatasourceId());
		try {
			if (genTableInfo.getGenColumnInfoList().stream().anyMatch(i -> "Y".equalsIgnoreCase(i.getTableLogic()))) {
				formInfoMapper.remove(formInfo);
			} else {
				formInfoMapper.delete(formInfo);
			}
		} finally {
			DynamicDataSourceContextHolder.clearDataSourceType();
		}

	}

	@Override
	public void batchRemove(Integer tableId, String ids) {
		FormInfo formInfo = new FormInfo().setTableId(tableId);
		GenTableInfo genTableInfo = genTableInfoService.getByIdWithChild(tableId);
		formInfo.setGenTableInfo(genTableInfo);
		DynamicDataSourceContextHolder.setDataSourceType(genTableInfo.getDatasourceId());


		//2.获取事务定义

//		DefaultTransactionDefinition def = new DefaultTransactionDefinition();

		//3.设置事务隔离级别，开启新事务

//		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

		//4.获得事务状态

//		TransactionStatus status = platformTransactionManager.getTransaction(def);
		try {
			Stream<String> stream = Stream.of(ids.split(StrUtil.COMMA)).filter(StrUtil::isNotBlank);
			if (genTableInfo.getGenColumnInfoList().stream().anyMatch(i -> "Y".equalsIgnoreCase(i.getTableLogic()))) {
				stream.forEach(
						i -> formInfoMapper.remove(
								formInfo.setId(Integer.valueOf(i))));
			} else {
				stream.forEach(
						i -> formInfoMapper.delete(
								formInfo.setId(Integer.valueOf(i))));
			}
//			platformTransactionManager.commit(status);
		} catch (Exception e) {
//			platformTransactionManager.rollback(status);
			log.error("batchRemove error", e);
		} finally {
			DynamicDataSourceContextHolder.clearDataSourceType();
		}
	}

}
